﻿using System.Collections.Generic;
using FairyGUI;
using System;
using UnityEngine;

public class FFixedRoomListPopup : MyWindow {

	GList _roomList;
    List<FixedRoom> _dataList;
	public Action<int> loadRoom ;
	protected override void OnInit(){
		base.OnInit();
	}
	public FFixedRoomListPopup(OneDelegate cb = default(OneDelegate)){
        this.contentPane = UIPackage.CreateObject("MapPackages", "FixedRoomListPopup").asCom;
		_roomList = this.contentPane.GetChild("roomList").asList;

		_roomList.itemRenderer = (int index, GObject item) => {
			FixedRoom data = _dataList[index];
            item.asCom.GetChild("nameTextField").asTextField.text = data.name;
            item.asCom.GetChild("rectTextField").asTextField.text = string.Format("{0} * {1}",data.width,data.height); 
            // item.asCom.GetChild("themeTextField").asTextField.text = data.id.ToString();
            // item.asCom.GetChild("bgmTextField").asTextField.text = data.id.ToString();
        };

		this.contentPane.GetChild("loadBtn").asButton.onClick.Add(() => {
			if(_roomList.selectedIndex == -1){
				FUIMain.TipPanel("请选择要读取的房间！");
				return;
			}
			
			if (loadRoom != null) {
                loadRoom(_roomList.selectedIndex);
                FUIMain.ClosePanel(GMConfig.PanelType.SelectRoomListPopup);
			} 
		});

		this.contentPane.GetChild("removeBtn").onClick.Add(() => {
			int index = _roomList.selectedIndex;
            if (index == -1)
            {
                FUIMain.TipPanel("请选择要删除的房间！");
                return;
            }
            FUIMain.TipPanel("是否确定删除本条数据？", (status) =>
            {
                if ((int)status == 1)
                {
					_dataList.RemoveAt(index);
					_roomList.RemoveChildAt(index);
					Utils.SaveByJson<List<FixedRoom>>(Application.dataPath, "fixedRoomList.json", _dataList);
				}
			});
		});
        if (cb != null){
			this.contentPane.GetChild("closeBtn").onClick.Add(() => {
				FUIMain.ClosePanel(GMConfig.PanelType.SelectRoomListPopup);
			});
		}else {
            this.contentPane.GetChild("loadBtn").visible = false;
            this.contentPane.GetChild("closeBtn").visible = false;
		}
	}
	protected override void OnShown(){
        _dataList = Utils.LoadByJson<List<FixedRoom>>(Application.dataPath, "fixedRoomList.json");
        if (_dataList == null) _dataList = new List<FixedRoom>();
        _roomList.numItems = _dataList.Count;
	}
}
